package logic

import (
	"fmt"
	"gopkg.in/mgo.v2/bson"
	"svvenus/conf"
	"svvenus/util/uttime"
	"svvenus/vgame/model"
	"svvenus/vpub/constants"
	"svvenus/zlog"
	"svvenus/znet/zpb"
	"time"
)

var (
	GlobalMails = make(map[string]*model.GlobalMailDoc) //全局邮件列表

)

func GlobalMailAdd(gmMail *zpb.GmGMailInfo) {
	gmail := new(model.GlobalMailDoc)
	gmail.Id = bson.NewObjectId()
	gmail.Title = gmMail.Title
	gmail.Body = gmMail.Body
	gmail.SenderTime = uttime.TimeStringToTime(gmMail.SenderTime)
	gmail.Awards = make([]conf.PcAward, 0)
	for _, i2 := range gmMail.Awards {
		gmail.Awards = append(gmail.Awards, PbAward2PcAward(i2))
	}
	if gmail.SenderTime.After(time.Now()) {
		gmail.Version = 0
	} else {
		ServerData.GlobalMailVersion++
		gmail.Version = ServerData.GlobalMailVersion
	}
	GlobalMails[gmail.IdString()] = gmail
}

// GlobalMailSaveAll
// @Description: 全局邮件存档
func GlobalMailSaveAll() {
	db := constants.MgoMain.New()
	defer db.Close()

	for _, i2 := range GlobalMails {
		err := db.SaveAuto(i2)
		if err != nil {
			zlog.Error(err)
		}
	}

}

// GlobalMailLoadAll
// @Description: 全局邮件读档
func GlobalMailLoadAll() {
	db := constants.MgoMain.New()
	defer db.Close()

	mails := make([]model.GlobalMailDoc, 0)
	err := db.GetAll(new(model.GlobalMailDoc).CollectionName(), bson.M{}, &mails)
	if err != nil {
		zlog.Error(err)
	}
	for idx, _ := range mails {
		mail := mails[idx]
		GlobalMails[mail.IdString()] = &mail
	}
	for _, mail := range GlobalMails {
		fmt.Println(mail)
	}

}

// SchedulePerMinuteServerMail
// @Description: 检测全服邮件
func SchedulePerMinuteServerMail() {
	dtNow := time.Now()
	for idx, gmail := range GlobalMails {
		//检测过期的全服邮件 超过30天
		if dtNow.After(gmail.SenderTime.AddDate(0,0,30)) {
			delete(GlobalMails, idx)
			continue
		}
		//检测定时发送的邮件是否已经到发送时间
		if gmail.Version == 0 {
			if dtNow.After(gmail.SenderTime) {
				ServerData.GlobalMailVersion++
				gmail.Version = ServerData.GlobalMailVersion
			}
		}
	}
}